package com.fwamgic.spark;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import scala.Tuple2;

import java.util.Arrays;

/**
 * 使用Java的Lambda表达式写Spark
 */
public class JavaLambdaWordCount {
    public static void main(String[] args) {
        //创建SparkConf
        SparkConf sparkConf = new SparkConf().setAppName("JavaLambdaWordCount");

        //创建JavaSparkContext
        JavaSparkContext jsc = new JavaSparkContext(sparkConf);

        //读取文件生成JavaRDD
        JavaRDD<String> lines = jsc.textFile(args[0]);

        //拍平操作
        JavaRDD<String> flated = lines.flatMap(line -> Arrays.asList(line.split("\\s")).iterator());

        //生成Tuple2
        JavaPairRDD<String, Integer> wordAndOne = flated.mapToPair(word -> Tuple2.apply(word, 1));

        //根据key进行聚合计数
        JavaPairRDD<String, Integer> reduced = wordAndOne.reduceByKey((x, y) -> x + y);

        //交换Tuple2中的元素位置，方便根据计数结果排序
        JavaPairRDD<Integer, String> swapMapToPair = reduced.mapToPair(tp -> tp.swap());

        //对计数结果进行排序
        JavaPairRDD<Integer, String> sorted = swapMapToPair.sortByKey(false);

        //再次调换Tuple2中元素的顺序
        JavaPairRDD<String, Integer> result = sorted.mapToPair(tp -> tp.swap());

        //输出结果到文件中
        result.saveAsTextFile(args[1]);

        //关闭
        jsc.stop();
    }
}
